//
//  TripsViewController.m
//  chanyou
//
//  Created by wanli on 14/12/30.
//  Copyright (c) 2014年 wanli. All rights reserved.
//

#import "TripsViewController.h"
#import "ConnectModel.h"
#import "TripsTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "TripsDetailViewController.h"
#import "TripsModel.h"
#import "UIScrollView+MJRefresh.h"
#import "Singleton.h"
#import "SDImageCache.h"
#define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)
#define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)


@interface TripsViewController ()<UITableViewDataSource, UITableViewDelegate>

@end

@implementation TripsViewController
- (void)dealloc
{
    [_tableArray release];
    [_tableView release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.tableArray = [NSMutableArray array];
        self.pageNum = 1;
        self.count = 10;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.backgroundColor = [UIColor blackColor];
    self.navigationController.navigationBar.translucent = YES;
    
    
    [self createView];
}

#pragma mark -
#pragma mark 刷新时重新获取网络数据
- (void)beginConnectWithPath:(NSString *)path test:(NSString *)test{
//    NSString *connectStr = [NSString stringWithFormat:@"http://chanyouji.com/api/trips/featured.json?page=%ld",_pageNum];
    
    __block TripsViewController *trips = self;
    
    [ConnectModel connectModelWithUrl:path parmaters:nil finished:^(NSData *data) {
        if ([test isEqualToString:@"ok"]) {
            [trips.tableArray removeAllObjects];
        }
        NSMutableArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        for (NSMutableDictionary *dic in array) {
            TripsModel *trips = [[TripsModel alloc] init];
            [trips setValuesForKeysWithDictionary:dic];
            [_tableArray addObject:trips];
            [trips release];
        }
        [trips.tableView reloadData];
    }];
}

- (void)createView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 110)];
//    NSLog(@"%f", self.view.frame.size.width);
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
 
    [_tableView registerClass:[TripsTableViewCell class] forCellReuseIdentifier:@"tripTableCell"];
    [self.view addSubview:_tableView];

    
    [self beginConnectWithPath:@"http://chanyouji.com/api/trips/featured.json?page=1" test:@""];
    [self.tableView addHeaderWithTarget:self action:@selector(reloadAction)];
    [self.tableView addFooterWithTarget:self action:@selector(addAction)];
    
}


#pragma mark -
#pragma mark UITableView协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_tableArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TripsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tripTableCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    TripsModel *dic = [_tableArray objectAtIndex:indexPath.row];

    cell.nameLabel.text = dic.name;
    cell.nameLabel.shadowColor = [UIColor grayColor];
    cell.nameLabel.highlighted = YES;
    NSString *dateStr = dic.start_date;
    NSString *dateString = [dateStr stringByReplacingOccurrencesOfString:@"-" withString:@"."];
    NSString *days = [NSString stringWithFormat:@"%@ | %@天",dateString, dic.days];
    cell.dateLabel.text = days;
    cell.dateLabel.shadowColor = [UIColor lightGrayColor];
    cell.dateLabel.highlighted = YES;
    
    NSDictionary *userDic = dic.user;
    NSString *userImgStr = [userDic objectForKey:@"image"];
    [cell.userImgView sd_setImageWithURL:[NSURL URLWithString:userImgStr] placeholderImage:[UIImage imageNamed:@"placeHold.png"]];
    
    NSString *coverStr = dic.front_cover_photo_url;
    [cell.backgroundImgView sd_setImageWithURL:[NSURL URLWithString:coverStr] placeholderImage:[UIImage imageNamed:@"placeHold.png"]];
    
    
    cell.userNameLabel.text = [NSString stringWithFormat:@" %@",  [dic.user objectForKey:@"name"]];
    [cell.backgroundImgView sd_setImageWithURL:[NSURL URLWithString:coverStr] placeholderImage:[UIImage imageNamed:@"placeHold.png"]];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return (SCREEN_WIDTH - 20) * 0.618;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TripsDetailViewController *tripsDetail = [[TripsDetailViewController alloc] init];
    TripsModel *trips = [_tableArray objectAtIndex:indexPath.row];
    tripsDetail.IdNum = [trips.id integerValue];
    tripsDetail.trips = trips;
    Singleton *share = [Singleton shareInstance];
    share.IdNum = [trips.id integerValue];

    
//    SideViewController *sideVC = [[[SideViewController alloc] init] autorelease];
//    sideVC.IdNum = [trips.id integerValue];
    
    [self.navigationController pushViewController:tripsDetail animated:YES];
    [[SDImageCache sharedImageCache] clearMemory];
    [tripsDetail release];
    
    NSLog(@"detail 1111 == %d", [tripsDetail retainCount]);
}


#pragma mark -
#pragma mark pullLoad
- (void)reloadAction
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self beginConnectWithPath:@"http://chanyouji.com/api/trips/featured.json?page=1" test:@"ok"];
        [self.tableView headerEndRefreshing];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    });

}

- (void)addAction
{
    _pageNum++;
    NSString *path = [NSString stringWithFormat:@"http://chanyouji.com/api/trips/featured.json?page=%ld", _pageNum];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self beginConnectWithPath:path test:@""];
        [self.tableView footerEndRefreshing];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    });
}

- (void)didReceiveMemoryWarning{
    [[SDImageCache sharedImageCache] clearMemory];
    [super didReceiveMemoryWarning];
    NSLog(@"fafafa");
//    if ([self.view window] == nil) {
//        self.view = nil;
//    }

//    if (self.isViewLoaded && !self.view.window)// 是否是正在使用的视图
//    {
//        // Add code to preserve data stored in the views that might be
//        // needed later.
//        
//        // Add code to clean up other strong references to the view in
//        // the view hierarchy.
//        self.view = nil;// 目的是再次进入时能够重新加载调用viewDidLoad函数。
//    }
    
    
}



@end
